package com.gali.leetcode.day27;

import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: gali
 * @Date: 2022-08-24 19:45
 * @Description:
 */
public class Solution {
    public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }
    /**
     *二叉树展开为链表
     * @param root
     */
    public void flatten(TreeNode root) {
        //前序遍历
        List<TreeNode> list = new ArrayList<>();
        preorderTraversal(root,list);
        int size = list.size();
        for (int i = 1; i < size; i++) {
            TreeNode prev=list.get(i-1);
            TreeNode curr=list.get(i);
            prev.left=null;
            prev.right=curr;
        }
    }

    private void preorderTraversal(TreeNode root, List<TreeNode> list) {
        if (root!=null){
            list.add(root);
            preorderTraversal(root.left,list);
            preorderTraversal(root.right,list);
        }
    }
}
